package com.example.choupaiapp.main.fragment;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.choupaiapp.R;
import com.example.choupaiapp.common.constant.Contacts;
import com.example.choupaiapp.common.finalokgo.callback.Callback;
import com.example.choupaiapp.common.finalokgo.request.RequestType;
import com.example.choupaiapp.common.ui.fragment.CommonFragment;
import com.example.choupaiapp.common.util.ContextUtil;
import com.example.choupaiapp.common.util.SharedPreferencesHelp;
import com.example.choupaiapp.common.util.Utils;
import com.example.choupaiapp.common.view.statusbar.StatusView;
import com.example.choupaiapp.main.activity.ChoseLoginActivity;
import com.example.choupaiapp.main.activity.find.FindBannerWebviewActivity;
import com.example.choupaiapp.main.activity.find.FindDetailActivity;
import com.example.choupaiapp.main.activity.find.FindPowerActivity;
import com.example.choupaiapp.main.activity.home.SearchActivity;
import com.example.choupaiapp.main.activity.home.SearchResultActivity;
import com.example.choupaiapp.main.bean.FindPowerBean;
import com.example.choupaiapp.main.bean.FindTabBean;
import com.example.choupaiapp.main.bean.SearchHotBean;
import com.example.choupaiapp.main.bean.UserInfoBean;
import com.example.choupaiapp.main.constant.Url;
import com.example.choupaiapp.main.fragment.find.FindChildFragment;
import com.example.choupaiapp.main.view.GlideImageLoader;
import com.flyco.tablayout.CoustomSlidingTabLayout;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.sunfusheng.marqueeview.MarqueeView;
import com.umeng.analytics.MobclickAgent;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by ASUS on 2019/10/30.
 */

public class FindFragment extends CommonFragment implements OnRefreshLoadMoreListener {

    @BindView(R.id.slide_tab)
    CoustomSlidingTabLayout slideTab;
    @BindView(R.id.viewpager)
    ViewPager viewpager;
    @BindView(R.id.top_ll)
    LinearLayout top_ll;
    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.title_banner)
    TextView title_banner;
    @BindView(R.id.titleBar)
    RelativeLayout titleBar;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.status_view)
    StatusView status_view;
    @BindView(R.id.apply_power)
    TextView apply_power;
    Unbinder unbinder;
    @BindView(R.id.marqueeView)
    MarqueeView marqueeView;
    @BindView(R.id.appbar)
    AppBarLayout appbar;
    @BindView(R.id.coordinator)
    CoordinatorLayout coordinator;


    private ArrayList<Fragment> mFragments = new ArrayList<>();
    private ArrayList<String> list = new ArrayList<>();
    private List<String> images = new ArrayList<>();
    private MyPagerAdapter mAdapter;
    private FindPowerBean mFindPowerBean;
    private UserInfoBean mUserInfoBean;
    private FindTabBean mFindTabBean;
    private int mPosition = 0;

    public static FindFragment newInstance() {
        return new FindFragment();
    }

    @SuppressLint("RestrictedApi")
    @Override
    protected View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_find, container, false);
        unbinder = ButterKnife.bind(this, view);

        EventBus.getDefault().register(this);

        refreshLayout.setOnRefreshLoadMoreListener(this);
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setRefreshHeader(new MaterialHeader(context).setColorSchemeResources(R.color.common_color));


        slideTab.setTextsize(13);
        slideTab.setTextSelectColor(Color.WHITE);
        slideTab.setTextUnselectColor(getResources().getColor(R.color.color_333));


        viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                slideTab.setmCurrentTab(position);
                slideTab.setmCurrentPositionOffset(positionOffset);
                slideTab.scrollToCurrentTab();
                slideTab.invalidate();

            }

            @Override
            public void onPageSelected(int position) {
                mPosition = position;
                slideTab.updateTabSelection(position);
                for (int i = 0; i < list.size(); i++) {
                    if (i == position) {
                        slideTab.getTitleView(i).setBackgroundResource(R.drawable.shape_333_oval);
                    } else {
                        slideTab.getTitleView(i).setBackgroundResource(R.drawable.shape_gray_oval);
                    }
                    ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) slideTab.getTitleView(i).getLayoutParams();
                    lp.leftMargin = 10;
                    slideTab.getTitleView(i).setLayoutParams(lp);

                }
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });
        slideTab.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                viewpager.setCurrentItem(position);
                mPosition = position;
            }

            @Override
            public void onTabReselect(int position) {

            }
        });


        mAdapter = new MyPagerAdapter(getChildFragmentManager());
        viewpager.setAdapter(mAdapter);

        marqueeView.setOnItemClickListener(new MarqueeView.OnItemClickListener() {
            @Override
            public void onItemClick(int position, TextView textView) {
                Bundle bundle = new Bundle();
                bundle.putString("name", textView.getText().toString());
                startActivity(SearchResultActivity.class, bundle);
            }
        });


        return view;
    }


    @Override
    protected void initData() {

        finalOkGo.request(RequestType.POST, Url.FIND_POWER, null, Url.FIND_POWER, new Callback<FindPowerBean>() {
            @Override
            public void onSuccess(FindPowerBean findPowerBean) {
                if (findPowerBean.getCode() == Contacts.SUCCESS) {
                    mFindPowerBean = findPowerBean;
                    apply_power.setText(findPowerBean.getApply().getButtonName());
                } else {
                    if (findPowerBean.getCode() == Contacts.TOKEN_EMPTY) {
                    } else {
                        showImageToas(findPowerBean.getMsg());
                    }
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                dismissDialog();
            }
        });

        finalOkGo.requestHead(RequestType.POSTHEAD, Url.SEARCH_HOT, null, Url.SEARCH_HOT, new Callback<SearchHotBean>() {
            @Override
            public void onSuccess(SearchHotBean searchHotBean) {
                dismissDialog();
                if (searchHotBean.getCode() == Contacts.SUCCESS) {
                    if (marqueeView.getMessages() != null && marqueeView.getMessages().size() != searchHotBean.getPage().getList().size()) {
                        marqueeView.startWithList(searchHotBean.getPage().getList());
                        marqueeView.startFlipping();
                    }
                } else {
                    if (searchHotBean.getCode() == Contacts.TOKEN_EMPTY) {
                    } else {
                        showImageToas(searchHotBean.getMsg());
                    }
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                dismissDialog();
            }
        });

        finalOkGo.request(RequestType.POST, Url.FIND_TAB_BANNER, null, Url.FIND_TAB_BANNER, new Callback<FindTabBean>() {
            @Override
            public void onSuccess(FindTabBean findTabBean) {
                if (findTabBean.getCode() == Contacts.SUCCESS) {
                    mFindTabBean = findTabBean;
                    images.clear();

                    for (int i = 0; i < findTabBean.getBannerList().size(); i++) {
                        images.add(findTabBean.getBannerList().get(i).getImage());
                    }

                    EventBus.getDefault().post("refresh_find_child");
                    if (mFragments.size() < findTabBean.getCategoriesList().size()) {
                        list.clear();
                        mFragments.clear();
                        for (int i = 0; i < findTabBean.getCategoriesList().size(); i++) {
                            list.add(findTabBean.getCategoriesList().get(i).getName());
                            FindChildFragment findChildFragment = FindChildFragment.newInstance(findTabBean.getCategoriesList().get(i).getId() + "");
                            mFragments.add(findChildFragment);
                        }

                        mAdapter.notifyDataSetChanged();

                        slideTab.setviewPager(viewpager);

                        slideTab.setmTitles(list);
                        slideTab.notifyDataSetChanged();


                        viewpager.setCurrentItem(0);
                        viewpager.setOffscreenPageLimit(3);


                        for (int i = 0; i < list.size(); i++) {
                            if (i == 0) {
                                slideTab.getTitleView(i).setBackgroundResource(R.drawable.shape_333_oval);
                            } else {
                                slideTab.getTitleView(i).setBackgroundResource(R.drawable.shape_gray_oval);
                            }
                            ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) slideTab.getTitleView(i).getLayoutParams();
                            lp.leftMargin = 10;
                            slideTab.getTitleView(i).setLayoutParams(lp);
                        }
                    }

                    banner.setOnBannerListener(new OnBannerListener() {
                        @Override
                        public void OnBannerClick(int position) {
                            MobclickAgent.onEvent(ContextUtil.getContext(), "bannerID");
                            if (findTabBean.getBannerList().get(position).getProvider() == 1) {
                                Bundle bundle = new Bundle();
                                bundle.putString("id", findTabBean.getBannerList().get(position).getResource() + "");
                                startActivity(FindDetailActivity.class, bundle);
                            } else if (findTabBean.getBannerList().get(position).getProvider() == 2) {
                                //H5
                                if (!TextUtils.isEmpty(findTabBean.getBannerList().get(position).getResource())) {
                                    Bundle bundle = new Bundle();
                                    bundle.putString("url", findTabBean.getBannerList().get(position).getResource() + "");
                                    startActivity(FindBannerWebviewActivity.class, bundle);
                                }
                            }
                        }
                    });


                    //设置banner样式
                    banner.setBannerStyle(BannerConfig.NOT_INDICATOR);
                    //设置图片加载器
                    banner.setImageLoader(new GlideImageLoader());
                    //设置图片集合
                    banner.setImages(images);
                    //设置banner动画效果
//                    banner.setBannerAnimation(Transformer.DepthPage);
                    //设置自动轮播，默认为true
                    banner.isAutoPlay(true);
                    //设置轮播时间
                    banner.setDelayTime(5000);
                    //banner设置方法全部调用完毕时最后调用
                    banner.start();
                    refreshLayout.finishRefresh();
                } else {
                    if (findTabBean.getCode() == Contacts.TOKEN_EMPTY) {
                    } else {
                        showImageToas(findTabBean.getMsg());
                    }
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
            }
        });


    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {

    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        initData();
    }

    private class MyPagerAdapter extends FragmentPagerAdapter {
        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public int getCount() {
            return mFragments.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return list.get(position);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
//            super.destroyItem(container, position, object);
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        unbinder.unbind();
    }


//    @Override
    @OnClick({R.id.apply_power, R.id.search})
    public void onViewClicked(View view) {
//        super.onViewClicked(view);
        if (Utils.isDoubleClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.apply_power:
                if (!TextUtils.isEmpty((String) SharedPreferencesHelp.get("token", ""))) {
                    if (mFindPowerBean != null) {
                        finalOkGo.requestHead(RequestType.GETHEAD, Url.GET_UERINFO, null, Url.GET_UERINFO, new Callback<UserInfoBean>() {
                            @Override
                            public void onSuccess(UserInfoBean userInfoBean) {
                                dismissDialog();
                                if (userInfoBean.getCode() == Contacts.SUCCESS) {
                                    SharedPreferencesHelp.putBean("userInfo", userInfoBean);
                                    mUserInfoBean = (UserInfoBean) SharedPreferencesHelp.getBean("userInfo");
                                    Bundle bundle = new Bundle();
                                    bundle.putString("title", mFindPowerBean.getApply().getButtonName());
                                    bundle.putString("url", mFindPowerBean.getApply().getUrl() + "?token=" + (String) SharedPreferencesHelp.get("token", "") + "&&isApply=" + userInfoBean.getUser().getIsApply());
                                    startActivity(FindPowerActivity.class, bundle);
                                } else {
                                    if (userInfoBean.getCode() == Contacts.TOKEN_EMPTY) {
                                    } else {
                                        showImageToas(userInfoBean.getMsg());
                                    }
                                }
                            }

                            @Override
                            public void onError(Response<String> response) {
                                super.onError(response);
                                dismissDialog();
                            }
                        });
                    }
                } else {
                    startActivity(ChoseLoginActivity.class);
                }
                break;
            case R.id.search:
                startActivity(SearchActivity.class);
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
    public void OnMessageEvent(String event) {
        if (event.equals("find_scollTo_top")) {
            scrollToTop();
            EventBus.getDefault().post("scollTo_find_top:" + mFindTabBean.getCategoriesList().get(mPosition).getId());
        } else if (event.equals("find_refresh_data")) {
//            scrollToTop();
            refreshLayout.autoRefresh();
            EventBus.getDefault().post("refresh_find_data:" + mFindTabBean.getCategoriesList().get(mPosition).getId());
        }
    }

    public void scrollToTop() {
        //拿到 appbar 的 behavior,让 appbar 滚动
        ViewGroup.LayoutParams layoutParams = appbar.getLayoutParams();
        CoordinatorLayout.Behavior behavior =
                ((CoordinatorLayout.LayoutParams) layoutParams).getBehavior();
        if (behavior instanceof AppBarLayout.Behavior) {
            AppBarLayout.Behavior appBarLayoutBehavior = (AppBarLayout.Behavior) behavior;
            //拿到下方tabs的y坐标，即为我要的偏移量
            float y = coordinator.getY();
            //注意传递负值
            appBarLayoutBehavior.setTopAndBottomOffset((int) -y);
        }
    }


    //如果你需要考虑更好的体验，可以这么操作
    @Override
    public void onResume() {
        super.onResume();
        //开始轮播
        banner.startAutoPlay();
        marqueeView.startFlipping();
    }


    @Override
    public void onPause() {
        super.onPause();
        //结束轮播
        banner.stopAutoPlay();
        marqueeView.stopFlipping();
    }
}
